<!--
 * @Date: 2021-12-23 15:43:01
 * @LastEditors: LeeKing
 * @LastEditTime: 2021-12-25 17:14:13
 * @FilePath: \hrsaas\src\components\UploadImage\index.vue
-->

<template>
  <div>
    <el-upload
      v-show="!isShowProgress"
      class="avatar-uploader"
      action="#"
      :http-request="onRequest"
      :on-preview="onPreview"
      :on-remove="onRemove"
      list-type="picture-card"
      :file-list="fileList"
      :before-upload="beforeAvatarUpload"
      accept="image/gif, image/png"
      :on-change="onChange"
      :limit="limit"
      :on-exceed="onExceed"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-progress v-if="isShowProgress" type="circle" :percentage="percentage" />
    <div slot="tip" class="el-upload__tip">只能上传gif/png</div>
    <el-dialog title="头像" :visible.sync="dialogVisible" width="50%">
      <img :src="imgUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID1sTothGZbMq3ze8LHwKSJtCG3YmkRr0s',
  SecretKey: 'dz3qNdcKAn9E2arra3GCrFMCl47sMZXE'
})

export default {
  props: {
    limit: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      fileList: [],
      dialogVisible: false,
      imgUrl: '',
      percentage: 0,
      isShowProgress: false
    }
  },

  created() {},

  methods: {
    onRequest(data) {
      this.isShowProgress = true
      this.id = setInterval(() => {
        if (this.percentage < 97) {
          this.percentage += 2
        } else {
          clearInterval(this.id)
          this.percentage = 99
        }
      }, 600)
      cos.putObject(
        {
          Bucket: 'hrsaas24-1308960753' /* 必须 */,
          Region: 'ap-shanghai' /* 存储桶所在地域，必须字段 */,
          Key: data.file.name /* 必须 */,
          StorageClass: 'STANDARD',
          Body: data.file, // 上传文件对象
          onProgress: (progressData) => {
            //
            if (progressData.percent === 1) {
              this.percentage = 100
              clearInterval(this.id)
              setTimeout(() => {
                this.isShowProgress = false
                this.percentage = 0
              }, 500)
            }
          }
        },
        (err, data) => {
          if (err) {
            this.isShowProgress = false
            this.$message.error('网络错误')
            this.fileList.splice(this.fileList.length - 1, 1)
          }
          if (!err && data.statusCode === 200) {
            this.$message.success('上传成功！')
            const fileLength = this.fileList.length - 1
            this.fileList[fileLength].url = 'https://' + data.Location
            this.$emit('on-success', this.fileList)
          }
        }
      )
    },
    // 超出提示
    onExceed() {
      this.$message.error('最多只能上传' + this.limit + '张图片！')
    },
    // 预览
    onPreview(file) {
      this.imgUrl = file.url
      this.dialogVisible = true
    },
    // 删除
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    // 图片上传大小校验
    beforeAvatarUpload(file) {
      const maxSize = 1 * 1024 * 1024
      const imgType = ['image/gif', 'image/png']
      if (!imgType.includes(file.type)) {
        this.$message.error('请上传正确格式的图片')
        return false
      }
      if (file.size > maxSize) {
        this.$message.error('请上传1MB以内的图片')
        return false
      }
    },
    onChange(file, fileList) {
      this.fileList = fileList
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
</style>
